import { ElMessage } from 'element-plus'

// 财务相关类型定义
export interface Voucher {
    id: string
    voucherNo: string
    voucherType: 'sales' | 'purchase' | 'refund' | 'adjustment'
    orderId?: string
    customerName: string
    totalAmount: number
    voucherDate: string
    status: 'draft' | 'pending' | 'approved' | 'rejected' | 'posted'
    summary: string
    entries: AccountingEntry[]
    createdAt: string
    updatedAt: string
}

export interface AccountingEntry {
    id: string
    accountCode: string
    accountName: string
    debitAmount: number
    creditAmount: number
    summary: string
    auxiliary?: string
    auxiliaryValue?: string
}

export interface Order {
    id: string
    orderNo: string
    orderType: 'sales' | 'purchase' | 'refund'
    customerName: string
    amount: number
    orderStatus: 'completed' | 'processing' | 'cancelled'
    createTime: string
    remark: string
}

export interface AuditRecord {
    id: string
    voucherId: string
    voucherNo: string
    auditor: string
    auditStatus: 'pending' | 'approved' | 'rejected' | 'posted'
    auditTime: string
    auditRemark: string
    auditLevel: string
    urgency: string
}

// 财务管理服务
import { ref, reactive } from 'vue'

// 会计科目类型
export interface AccountingSubject {
    id: string
    code: string
    name: string
    type: 'asset' | 'liability' | 'equity' | 'cost' | 'profit'
    auxiliaryType: string | null
    remark: string
    parentCode?: string
    level: number
}

// 辅助核算项
export interface AuxiliarySubject {
    id: string
    subjectCode: string
    auxiliaryCode: string
    auxiliaryName: string
    category: 'customer' | 'supplier' | 'bank' | 'department' | 'project' | 'employee' | 'other'
    status: 'active' | 'inactive'
}

// 完整的会计科目表
export const accountingSubjects: AccountingSubject[] = [
    // 资产类
    { id: '1', code: '1001', name: '库存现金', type: 'asset', auxiliaryType: null, remark: '现金科目', level: 1 },
    { id: '2', code: '1002', name: '银行存款', type: 'asset', auxiliaryType: 'bank', remark: '银行科目', level: 1 },
    { id: '3', code: '1003', name: '备用金', type: 'asset', auxiliaryType: 'employee', remark: '备用金科目', level: 1 },
    { id: '4', code: '1122', name: '应收账款', type: 'asset', auxiliaryType: 'customer', remark: '应收科目', level: 1 },
    { id: '5', code: '1221', name: '预付账款', type: 'asset', auxiliaryType: 'supplier', remark: '预付科目', level: 1 },
    { id: '6', code: '1405', name: '原材料', type: 'asset', auxiliaryType: null, remark: '存货科目', level: 1 },
    { id: '7', code: '1406', name: '库存商品', type: 'asset', auxiliaryType: null, remark: '存货科目', level: 1 },
    { id: '8', code: '1501', name: '固定资产', type: 'asset', auxiliaryType: 'department', remark: '固定资产科目', level: 1 },
    { id: '9', code: '1601', name: '无形资产', type: 'asset', auxiliaryType: null, remark: '无形资产科目', level: 1 },

    // 负债类
    { id: '10', code: '2001', name: '短期借款', type: 'liability', auxiliaryType: 'bank', remark: '短期借款科目', level: 1 },
    { id: '11', code: '2202', name: '应付账款', type: 'liability', auxiliaryType: 'supplier', remark: '应付科目', level: 1 },
    { id: '12', code: '2203', name: '预收账款', type: 'liability', auxiliaryType: 'customer', remark: '预收科目', level: 1 },
    { id: '13', code: '2204', name: '应交税费', type: 'liability', auxiliaryType: null, remark: '应交税费', level: 1 },
    { id: '14', code: '2205', name: '其他应付款', type: 'liability', auxiliaryType: null, remark: '其他应付款', level: 1 },
    { id: '15', code: '2211', name: '应付职工薪酬', type: 'liability', auxiliaryType: 'employee', remark: '职工薪酬科目', level: 1 },

    // 所有者权益类
    { id: '16', code: '3001', name: '实收资本', type: 'equity', auxiliaryType: null, remark: '资本科目', level: 1 },
    { id: '17', code: '3002', name: '资本公积', type: 'equity', auxiliaryType: null, remark: '资本公积', level: 1 },
    { id: '18', code: '3003', name: '盈余公积', type: 'equity', auxiliaryType: null, remark: '盈余公积', level: 1 },
    { id: '19', code: '3004', name: '未分配利润', type: 'equity', auxiliaryType: null, remark: '未分配利润', level: 1 },
    { id: '20', code: '6301', name: '本年利润', type: 'equity', auxiliaryType: null, remark: '利润科目', level: 1 },
    { id: '21', code: '6401', name: '利润分配', type: 'equity', auxiliaryType: null, remark: '利润分配', level: 1 },

    // 成本类
    { id: '22', code: '4001', name: '主营业务成本', type: 'cost', auxiliaryType: 'project', remark: '销售成本科目', level: 1 },
    { id: '23', code: '4002', name: '劳务成本', type: 'cost', auxiliaryType: null, remark: '劳务成本', level: 1 },
    { id: '24', code: '4003', name: '制造费用', type: 'cost', auxiliaryType: 'department', remark: '制造费用', level: 1 },
    { id: '25', code: '4004', name: '研发支出', type: 'cost', auxiliaryType: 'project', remark: '研发支出', level: 1 },

    // 损益类
    { id: '26', code: '5001', name: '销售费用', type: 'profit', auxiliaryType: 'department', remark: '销售费用科目', level: 1 },
    { id: '27', code: '5002', name: '管理费用', type: 'profit', auxiliaryType: 'department', remark: '管理费用科目', level: 1 },
    { id: '28', code: '5003', name: '财务费用', type: 'profit', auxiliaryType: null, remark: '财务费用科目', level: 1 },
    { id: '29', code: '6001', name: '主营业务收入', type: 'profit', auxiliaryType: 'customer', remark: '销售收入科目', level: 1 },
    { id: '30', code: '6002', name: '其他业务收入', type: 'profit', auxiliaryType: null, remark: '其他收入科目', level: 1 },
    { id: '31', code: '6101', name: '营业外收入', type: 'profit', auxiliaryType: null, remark: '营业外收入科目', level: 1 },
    { id: '32', code: '6102', name: '营业外支出', type: 'profit', auxiliaryType: null, remark: '营业外支出科目', level: 1 },
    { id: '33', code: '6201', name: '所得税费用', type: 'profit', auxiliaryType: null, remark: '所得税科目', level: 1 }
]

// 辅助核算项数据
export const auxiliarySubjects: AuxiliarySubject[] = [
    // 银行账户
    { id: '1', subjectCode: '1002', auxiliaryCode: '001', auxiliaryName: '三菱东京UFJ银行', category: 'bank', status: 'active' },
    { id: '2', subjectCode: '1002', auxiliaryCode: '002', auxiliaryName: 'ゆうちょ银行', category: 'bank', status: 'active' },
    { id: '3', subjectCode: '1002', auxiliaryCode: '003', auxiliaryName: '三井住友银行', category: 'bank', status: 'active' },

    // 客户
    { id: '4', subjectCode: '1122', auxiliaryCode: '001', auxiliaryName: '田中太郎', category: 'customer', status: 'active' },
    { id: '5', subjectCode: '1122', auxiliaryCode: '002', auxiliaryName: '佐藤花子', category: 'customer', status: 'active' },
    { id: '6', subjectCode: '1122', auxiliaryCode: '003', auxiliaryName: '山田次郎', category: 'customer', status: 'active' },
    { id: '7', subjectCode: '1122', auxiliaryCode: '004', auxiliaryName: '鈴木美咲', category: 'customer', status: 'active' },

    // 供应商
    { id: '8', subjectCode: '1221', auxiliaryCode: '001', auxiliaryName: 'JAA拍卖', category: 'supplier', status: 'active' },
    { id: '9', subjectCode: '1221', auxiliaryCode: '002', auxiliaryName: 'エコリング', category: 'supplier', status: 'active' },
    { id: '10', subjectCode: '1221', auxiliaryCode: '003', auxiliaryName: 'ベストライフ', category: 'supplier', status: 'active' },

    // 部门
    { id: '11', subjectCode: '1501', auxiliaryCode: '001', auxiliaryName: '销售部', category: 'department', status: 'active' },
    { id: '12', subjectCode: '1501', auxiliaryCode: '002', auxiliaryName: '采购部', category: 'department', status: 'active' },
    { id: '13', subjectCode: '1501', auxiliaryCode: '003', auxiliaryName: '财务部', category: 'department', status: 'active' },
    { id: '14', subjectCode: '1501', auxiliaryCode: '004', auxiliaryName: '人事部', category: 'department', status: 'active' },

    // 项目
    { id: '15', subjectCode: '4001', auxiliaryCode: '001', auxiliaryName: '电子产品项目', category: 'project', status: 'active' },
    { id: '16', subjectCode: '4001', auxiliaryCode: '002', auxiliaryName: '服装项目', category: 'project', status: 'active' },
    { id: '17', subjectCode: '4004', auxiliaryCode: '001', auxiliaryName: '新功能开发', category: 'project', status: 'active' },

    // 员工
    { id: '18', subjectCode: '1003', auxiliaryCode: '001', auxiliaryName: '张三', category: 'employee', status: 'active' },
    { id: '19', subjectCode: '1003', auxiliaryCode: '002', auxiliaryName: '李四', category: 'employee', status: 'active' },
    { id: '20', subjectCode: '2211', auxiliaryCode: '001', auxiliaryName: '王五', category: 'employee', status: 'active' },
    { id: '21', subjectCode: '2211', auxiliaryCode: '002', auxiliaryName: '赵六', category: 'employee', status: 'active' }
]

// 获取会计科目
export function getAccountingSubjects() {
    return accountingSubjects
}

// 根据科目编码获取科目信息
export function getSubjectByCode(code: string): AccountingSubject | undefined {
    return accountingSubjects.find(subject => subject.code === code)
}

// 根据科目类型获取科目列表
export function getSubjectsByType(type: string): AccountingSubject[] {
    return accountingSubjects.filter(subject => subject.type === type)
}

// 获取辅助核算项
export function getAuxiliarySubjects(subjectCode: string): AuxiliarySubject[] {
    return auxiliarySubjects.filter(aux => aux.subjectCode === subjectCode && aux.status === 'active')
}

// 根据辅助核算类型获取科目列表
export function getSubjectsByAuxiliaryType(auxiliaryType: string): AccountingSubject[] {
    return accountingSubjects.filter(subject => subject.auxiliaryType === auxiliaryType)
}

// 生成会计分录
export function generateAccountingEntries(orderType: string, amount: number, customerName: string, auxiliarySubjects: AuxiliarySubject[]) {
    const entries = []

    if (orderType === 'sales') {
        // 销售订单：借：银行存款/应收账款，贷：主营业务收入
        const cashSubject = getSubjectByCode('1002')
        const revenueSubject = getSubjectByCode('6001')

        if (cashSubject) {
            entries.push({
                id: Date.now().toString(),
                accountCode: cashSubject.code,
                accountName: cashSubject.name,
                debitAmount: amount,
                creditAmount: 0,
                summary: `收到${customerName}商品销售收入`,
                auxiliary: cashSubject.auxiliaryType,
                auxiliaryValue: auxiliarySubjects.find(aux => aux.category === 'bank')?.auxiliaryName || '默认银行账户'
            })
        }

        if (revenueSubject) {
            entries.push({
                id: (Date.now() + 1).toString(),
                accountCode: revenueSubject.code,
                accountName: revenueSubject.name,
                debitAmount: 0,
                creditAmount: amount,
                summary: `${customerName}商品销售收入`,
                auxiliary: revenueSubject.auxiliaryType,
                auxiliaryValue: customerName
            })
        }
    } else if (orderType === 'purchase') {
        // 采购订单：借：库存商品，贷：银行存款/应付账款
        const inventorySubject = getSubjectByCode('1406')
        const cashSubject = getSubjectByCode('1002')

        if (inventorySubject) {
            entries.push({
                id: Date.now().toString(),
                accountCode: inventorySubject.code,
                accountName: inventorySubject.name,
                debitAmount: amount,
                creditAmount: 0,
                summary: `采购商品入库`,
                auxiliary: inventorySubject.auxiliaryType,
                auxiliaryValue: null
            })
        }

        if (cashSubject) {
            entries.push({
                id: (Date.now() + 1).toString(),
                accountCode: cashSubject.code,
                accountName: cashSubject.name,
                debitAmount: 0,
                creditAmount: amount,
                summary: `支付采购货款`,
                auxiliary: cashSubject.auxiliaryType,
                auxiliaryValue: auxiliarySubjects.find(aux => aux.category === 'bank')?.auxiliaryName || '默认银行账户'
            })
        }
    } else if (orderType === 'refund') {
        // 退款订单：借：主营业务收入，贷：银行存款
        const revenueSubject = getSubjectByCode('6001')
        const cashSubject = getSubjectByCode('1002')

        if (revenueSubject) {
            entries.push({
                id: Date.now().toString(),
                accountCode: revenueSubject.code,
                accountName: revenueSubject.name,
                debitAmount: Math.abs(amount),
                creditAmount: 0,
                summary: `商品退货退款`,
                auxiliary: revenueSubject.auxiliaryType,
                auxiliaryValue: customerName
            })
        }

        if (cashSubject) {
            entries.push({
                id: (Date.now() + 1).toString(),
                accountCode: cashSubject.code,
                accountName: cashSubject.name,
                debitAmount: 0,
                creditAmount: Math.abs(amount),
                summary: `支付退款`,
                auxiliary: cashSubject.auxiliaryType,
                auxiliaryValue: auxiliarySubjects.find(aux => aux.category === 'bank')?.auxiliaryName || '默认银行账户'
            })
        }
    }

    return entries
}

// 验证会计分录平衡
export function validateEntriesBalance(entries: any[]): boolean {
    const totalDebit = entries.reduce((sum, entry) => sum + (entry.debitAmount || 0), 0)
    const totalCredit = entries.reduce((sum, entry) => sum + (entry.creditAmount || 0), 0)
    return Math.abs(totalDebit - totalCredit) < 0.01 // 允许0.01的误差
}

// 获取科目类型的中文名称
export function getSubjectTypeName(type: string): string {
    const typeNames: Record<string, string> = {
        'asset': '资产',
        'liability': '负债',
        'equity': '所有者权益',
        'cost': '成本',
        'profit': '损益'
    }
    return typeNames[type] || type
}

// 获取辅助核算类型的中文名称
export function getAuxiliaryTypeName(type: string): string {
    const typeNames: Record<string, string> = {
        'customer': '客户',
        'supplier': '供应商',
        'bank': '银行账户',
        'department': '部门',
        'project': '项目',
        'employee': '员工',
        'other': '其他'
    }
    return typeNames[type] || type
}

// 财务服务类
class FinanceService {
    private baseUrl = '/api/finance'

    /**
     * 获取凭证列表
     */
    async getVouchers(params: {
        page?: number
        pageSize?: number
        voucherNo?: string
        voucherType?: string
        status?: string
        dateRange?: string[]
    }): Promise<{ data: Voucher[], total: number }> {
        try {
            // 模拟API调用
            await new Promise(resolve => setTimeout(resolve, 500))

            // 模拟数据
            const mockVouchers: Voucher[] = [
                {
                    id: '1',
                    voucherNo: 'V202401001',
                    voucherType: 'sales',
                    orderId: 'ORD202401001',
                    customerName: '田中太郎',
                    totalAmount: 15000,
                    voucherDate: '2024-01-15',
                    status: 'approved',
                    summary: '商品销售收入',
                    entries: [
                        {
                            id: '1',
                            accountCode: '1001',
                            accountName: '库存现金',
                            debitAmount: 0,
                            creditAmount: 15000,
                            summary: '收到商品销售收入'
                        },
                        {
                            id: '2',
                            accountCode: '6001',
                            accountName: '主营业务收入',
                            debitAmount: 0,
                            creditAmount: 15000,
                            summary: '商品销售收入'
                        }
                    ],
                    createdAt: '2024-01-15T10:00:00Z',
                    updatedAt: '2024-01-15T14:30:00Z'
                },
                {
                    id: '2',
                    voucherNo: 'V202401002',
                    voucherType: 'purchase',
                    orderId: 'ORD202401002',
                    customerName: '佐藤花子',
                    totalAmount: 8500,
                    voucherDate: '2024-01-16',
                    status: 'draft',
                    summary: '商品采购成本',
                    entries: [
                        {
                            id: '3',
                            accountCode: '1405',
                            accountName: '库存商品',
                            debitAmount: 8500,
                            creditAmount: 0,
                            summary: '商品采购入库'
                        },
                        {
                            id: '4',
                            accountCode: '1001',
                            accountName: '库存现金',
                            debitAmount: 0,
                            creditAmount: 8500,
                            summary: '支付采购货款'
                        }
                    ],
                    createdAt: '2024-01-16T09:00:00Z',
                    updatedAt: '2024-01-16T09:00:00Z'
                }
            ]

            return {
                data: mockVouchers,
                total: mockVouchers.length
            }
        } catch (error) {
            console.error('获取凭证列表失败:', error)
            ElMessage.error('获取凭证列表失败')
            return { data: [], total: 0 }
        }
    }

    /**
     * 根据订单自动生成凭证
     */
    async generateVoucherFromOrder(order: Order): Promise<Voucher | null> {
        try {
            // 模拟API调用
            await new Promise(resolve => setTimeout(resolve, 800))

            // 根据订单类型生成对应的会计分录
            const entries = this.generateAccountingEntries(order)

            const voucher: Voucher = {
                id: Date.now().toString(),
                voucherNo: `V${new Date().getFullYear()}${String(Date.now()).slice(-5)}`,
                voucherType: order.orderType,
                orderId: order.id,
                customerName: order.customerName,
                totalAmount: Math.abs(order.amount),
                voucherDate: new Date().toISOString().split('T')[0],
                status: 'draft',
                summary: this.generateVoucherSummary(order),
                entries,
                createdAt: new Date().toISOString(),
                updatedAt: new Date().toISOString()
            }

            return voucher
        } catch (error) {
            console.error('根据订单生成凭证失败:', error)
            ElMessage.error('生成凭证失败')
            return null
        }
    }

    /**
     * 生成会计分录
     */
    private generateAccountingEntries(order: Order): AccountingEntry[] {
        const entries: AccountingEntry[] = []

        if (order.orderType === 'sales') {
            // 销售订单：借现金/银行存款，贷主营业务收入
            entries.push(
                {
                    id: Date.now().toString(),
                    accountCode: '1001',
                    accountName: '库存现金',
                    debitAmount: Math.abs(order.amount),
                    creditAmount: 0,
                    summary: '收到商品销售收入'
                },
                {
                    id: (Date.now() + 1).toString(),
                    accountCode: '6001',
                    accountName: '主营业务收入',
                    debitAmount: 0,
                    creditAmount: Math.abs(order.amount),
                    summary: '商品销售收入'
                }
            )
        } else if (order.orderType === 'purchase') {
            // 采购订单：借库存商品，贷现金/银行存款
            entries.push(
                {
                    id: Date.now().toString(),
                    accountCode: '1405',
                    accountName: '库存商品',
                    debitAmount: Math.abs(order.amount),
                    creditAmount: 0,
                    summary: '商品采购入库'
                },
                {
                    id: (Date.now() + 1).toString(),
                    accountCode: '1001',
                    accountName: '库存现金',
                    debitAmount: 0,
                    creditAmount: Math.abs(order.amount),
                    summary: '支付采购货款'
                }
            )
        } else if (order.orderType === 'refund') {
            // 退款订单：借主营业务收入，贷现金/银行存款
            entries.push(
                {
                    id: Date.now().toString(),
                    accountCode: '6001',
                    accountName: '主营业务收入',
                    debitAmount: Math.abs(order.amount),
                    creditAmount: 0,
                    summary: '商品退货退款'
                },
                {
                    id: (Date.now() + 1).toString(),
                    accountCode: '1001',
                    accountName: '库存现金',
                    debitAmount: 0,
                    creditAmount: Math.abs(order.amount),
                    summary: '支付退款'
                }
            )
        }

        return entries
    }

    /**
     * 生成凭证摘要
     */
    private generateVoucherSummary(order: Order): string {
        const summaries: Record<string, string> = {
            sales: '商品销售收入',
            purchase: '商品采购成本',
            refund: '商品退货退款'
        }
        return summaries[order.orderType] || '其他业务'
    }

    /**
     * 保存凭证
     */
    async saveVoucher(voucher: Voucher): Promise<boolean> {
        try {
            // 模拟API调用
            await new Promise(resolve => setTimeout(resolve, 1000))

            // 验证借贷平衡
            if (!this.validateVoucherBalance(voucher)) {
                ElMessage.error('凭证借贷不平衡，请检查')
                return false
            }

            // 保存到localStorage（实际应该保存到API）
            const vouchers = JSON.parse(localStorage.getItem('vouchers') || '[]')
            const existingIndex = vouchers.findIndex((v: Voucher) => v.id === voucher.id)

            if (existingIndex > -1) {
                vouchers[existingIndex] = voucher
            } else {
                vouchers.push(voucher)
            }

            localStorage.setItem('vouchers', JSON.stringify(vouchers))

            ElMessage.success('凭证保存成功')
            return true
        } catch (error) {
            console.error('保存凭证失败:', error)
            ElMessage.error('保存凭证失败')
            return false
        }
    }

    /**
     * 验证凭证借贷平衡
     */
    private validateVoucherBalance(voucher: Voucher): boolean {
        const totalDebit = voucher.entries.reduce((sum, entry) => sum + (entry.debitAmount || 0), 0)
        const totalCredit = voucher.entries.reduce((sum, entry) => sum + (entry.creditAmount || 0), 0)
        return Math.abs(totalDebit - totalCredit) < 0.01 // 允许0.01的误差
    }

    /**
     * 获取订单列表
     */
    async getOrders(params: {
        page?: number
        pageSize?: number
        orderNo?: string
        orderType?: string
        orderStatus?: string
    }): Promise<{ data: Order[], total: number }> {
        try {
            // 模拟API调用
            await new Promise(resolve => setTimeout(resolve, 500))

            // 模拟订单数据
            const mockOrders: Order[] = [
                {
                    id: 'ORD202401001',
                    orderNo: 'ORD202401001',
                    orderType: 'sales',
                    customerName: '田中太郎',
                    amount: 15000,
                    orderStatus: 'completed',
                    createTime: '2024-01-15 10:30:00',
                    remark: '商品销售收入'
                },
                {
                    id: 'ORD202401002',
                    orderNo: 'ORD202401002',
                    orderType: 'purchase',
                    customerName: '佐藤花子',
                    amount: 8500,
                    orderStatus: 'completed',
                    createTime: '2024-01-16 14:20:00',
                    remark: '商品采购成本'
                },
                {
                    id: 'ORD202401003',
                    orderNo: 'ORD202401003',
                    orderType: 'sales',
                    customerName: '山田次郎',
                    amount: 22000,
                    orderStatus: 'completed',
                    createTime: '2024-01-17 09:15:00',
                    remark: '电子产品销售'
                },
                {
                    id: 'ORD202401004',
                    orderNo: 'ORD202401004',
                    orderType: 'refund',
                    customerName: '鈴木美咲',
                    amount: -5000,
                    orderStatus: 'completed',
                    createTime: '2024-01-18 16:45:00',
                    remark: '商品退货退款'
                }
            ]

            return {
                data: mockOrders,
                total: mockOrders.length
            }
        } catch (error) {
            console.error('获取订单列表失败:', error)
            ElMessage.error('获取订单列表失败')
            return { data: [], total: 0 }
        }
    }

    /**
     * 获取审核记录
     */
    async getAuditRecords(params: {
        page?: number
        pageSize?: number
        voucherNo?: string
        auditStatus?: string
        auditor?: string
        auditDateRange?: string[]
    }): Promise<{ data: AuditRecord[], total: number }> {
        try {
            // 模拟API调用
            await new Promise(resolve => setTimeout(resolve, 500))

            // 模拟审核记录数据
            const mockAuditRecords: AuditRecord[] = [
                {
                    id: '1',
                    voucherId: '1',
                    voucherNo: 'V202401001',
                    auditor: '张财务',
                    auditStatus: 'approved',
                    auditTime: '2024-01-16 14:30:00',
                    auditRemark: '审核通过，金额正确',
                    auditLevel: 'level1',
                    urgency: 'normal'
                },
                {
                    id: '2',
                    voucherId: '2',
                    voucherId: '2',
                    voucherNo: 'V202401002',
                    auditor: '李经理',
                    auditStatus: 'pending',
                    auditTime: '',
                    auditRemark: '',
                    auditLevel: 'level1',
                    urgency: 'normal'
                }
            ]

            return {
                data: mockAuditRecords,
                total: mockAuditRecords.length
            }
        } catch (error) {
            console.error('获取审核记录失败:', error)
            ElMessage.error('获取审核记录失败')
            return { data: [], total: 0 }
        }
    }

    /**
     * 提交审核
     */
    async submitAudit(auditData: {
        voucherId: string
        auditResult: 'approved' | 'rejected'
        auditRemark: string
        auditLevel: string
        urgency: string
    }): Promise<boolean> {
        try {
            // 模拟API调用
            await new Promise(resolve => setTimeout(resolve, 800))

            ElMessage.success('审核提交成功')
            return true
        } catch (error) {
            console.error('提交审核失败:', error)
            ElMessage.error('提交审核失败')
            return false
        }
    }

    /**
     * 过账
     */
    async postVoucher(voucherId: string): Promise<boolean> {
        try {
            // 模拟API调用
            await new Promise(resolve => setTimeout(resolve, 1000))

            ElMessage.success('过账成功')
            return true
        } catch (error) {
            console.error('过账失败:', error)
            ElMessage.error('过账失败')
            return false
        }
    }

    /**
     * 获取凭证详情
     */
    async getVoucherDetail(voucherId: string): Promise<Voucher | null> {
        try {
            // 模拟API调用
            await new Promise(resolve => setTimeout(resolve, 500))

            // 从localStorage获取凭证数据
            const vouchers = JSON.parse(localStorage.getItem('vouchers') || '[]')
            const voucher = vouchers.find((v: Voucher) => v.id === voucherId)

            return voucher || null
        } catch (error) {
            console.error('获取凭证详情失败:', error)
            ElMessage.error('获取凭证详情失败')
            return null
        }
    }

    /**
     * 删除凭证
     */
    async deleteVoucher(voucherId: string): Promise<boolean> {
        try {
            // 模拟API调用
            await new Promise(resolve => setTimeout(resolve, 500))

            // 从localStorage删除凭证
            const vouchers = JSON.parse(localStorage.getItem('vouchers') || '[]')
            const filteredVouchers = vouchers.filter((v: Voucher) => v.id !== voucherId)
            localStorage.setItem('vouchers', JSON.stringify(filteredVouchers))

            ElMessage.success('凭证删除成功')
            return true
        } catch (error) {
            console.error('删除凭证失败:', error)
            ElMessage.error('删除凭证失败')
            return false
        }
    }

    /**
     * 导出凭证数据
     */
    async exportVouchers(params: {
        voucherNo?: string
        voucherType?: string
        status?: string
        dateRange?: string[]
    }): Promise<boolean> {
        try {
            // 模拟导出API调用
            await new Promise(resolve => setTimeout(resolve, 2000))

            ElMessage.success('导出成功')
            return true
        } catch (error) {
            console.error('导出凭证失败:', error)
            ElMessage.error('导出凭证失败')
            return false
        }
    }
}

// 导出服务实例
export const financeService = new FinanceService()
